<template>
  <div style="display: flex" class="uploadImg">
    <!-- 图片预览 -->
    <div style="display: flex; flex-wrap: wrap">
      <div class="demo-image__preview" v-for="(item, index) in fileLis" :key="index">
        <img @click="onDelImg(item)" class="deleteImg" src="@/assets/images/delete.png" alt="" />
        <el-image class="elImage" :src="item.url" :preview-src-list="previewimg(item)"> </el-image>
      </div>
      <el-upload
        v-show="fileLis.length != limit"
        action="#"
        :show-file-list="false"
        :accept="accept"
        :auto-upload="false"
        list-type="picture-card"
        :on-change="onChange"
        :limit="limit"
        :file-list="fileLis"
      >
        <el-icon><Plus /></el-icon>
        <template #tip>
          <div class="el-upload__tip">{{ describe }}</div>
        </template>
      </el-upload>
    </div>
  </div>
</template>
   
<script setup lang='ts'>
const props = defineProps({
  limit: {
    // 最大上传个数
    type: Number,
    default: 0
  },
  describe: {
    // 描述文件
    type: String,
    default: '只能上传jpg/png文件，且不超过500KB'
  },
  accept: {
    // 文件类型
    type: String,
    default: '.png, .jpg'
  }
});
const fileLis = ref<any>([]);
const previewimg = computed(() => {
  return function (data: any) {
    let res = [data.url];
    return res;
  };
});
const onChange = (file: any) => {
  const fileType = /\.(jpg|png|jpeg)$/.test(file.name);
  const isLt500k = file.size / 1024 < 500;
  if (!fileType) {
    onDelImg(file);
    ElMessage.warning("仅支持上传jpg、png格式的图片,请重新上传");
    return;
  }
  if (!isLt500k) {
    ElMessage.warning("上传的图片不超过500kb,请重新上传");
    return;
  }
  fileLis.value.push(file);
};
const onDelImg = (file: any) => {
  const newArray = fileLis.value.filter((element, index) => element.uid !== file.uid);
  fileLis.value = newArray;
};
defineExpose({
  fileLis
})
</script>
<style scoped lang='scss'>
.demo-image__preview {
  position: relative;
  margin-right: 10px;
  .deleteImg {
    z-index: 100;
    width: 40px;
    height: 40px;
    position: absolute;
    top: -0px;
    left: 110px;
    cursor: pointer;
  }
  .elImage {
    border: 1px solid #eee;
    border-radius: 10px;
    width: 150px;
    height: 150px;
  }
}
</style>